package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.domain.AnalysisConfigParamDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisConfigParamDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.rpc.api.AnalysisConfigParamRpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * created by wangjunfu on 2018-11-26 15:04:12
 */
@Service
public class AnalysisConfigParamManageService {

    private final static Logger logger = LoggerFactory.getLogger(AnalysisConfigParamManageService.class);

    private final AnalysisConfigParamRpcService rpcService;
    private final AHelpManageService helpService;
    private final Cache jedisCache;

    @Autowired
    public AnalysisConfigParamManageService(AnalysisConfigParamRpcService rpcService, AHelpManageService helpService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.helpService = helpService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public AnalysisConfigParamDTO insert(AnalysisConfigParamDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(AnalysisConfigParamDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新缓存
            refreshCacheById(objDTO.getId());
        }
        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(AnalysisConfigParamDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //单体刷新
        if (isNext && objDTOQuery.getW_id() != null) {
            refreshCacheById(objDTOQuery.getW_id());
        }

        //批量刷新缓存
        if (isNext && objDTOQuery.getIds() != null) {
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshCacheByIdList(list);
        }
        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);
        if (isNext) {
            // 刷新缓存
            refreshCacheById(id);
        }
        return isNext;
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        AnalysisConfigParamDTOQuery query = new AnalysisConfigParamDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        Boolean isNext = rpcService.updateInfoByQuery(query);
        if (isNext) {
            // 刷新缓存
            refreshCacheByIdList(idList);
        }
        return isNext;
    }

    // 通过ID获取
    public AnalysisConfigParamDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public AnalysisConfigParamDTO getByQuery(AnalysisConfigParamDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<AnalysisConfigParamDTO> getForPage(AnalysisConfigParamDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        AnalysisConfigParamDTO obj = new AnalysisConfigParamDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    /**
     * 通过参数key获取参数
     *
     * @param key key
     * @return obj
     */
    public AnalysisConfigParamDTO getByParamKey(String key) {
        AnalysisConfigParamDTOQuery query = new AnalysisConfigParamDTOQuery();
        query.setParamKey(key);
        query.setDeleteFlag(0);

        return getByQuery(query);
    }

    // 返回字符串
    public String getByParamKey(String key, String defaultValue) {
        AnalysisConfigParamDTO dto = getFromCacheKey(key);
        if (dto == null) {
            return defaultValue;
        }

        return dto.getParamValue();
    }

    // 返回整型
    public Integer getByParamKey(String key, Integer defaultValue) {
        AnalysisConfigParamDTO dto = getFromCacheKey(key);
        if (dto == null) {
            return defaultValue;
        }

        return Integer.valueOf(dto.getParamValue());
    }

    // 返回字符串
    public String getParmValueByParamKey(String key, String defaultValue) {
        AnalysisConfigParamDTO dto = getFromCacheKey(key);
        if (dto == null) {
            return defaultValue;
        }

        return dto.getParamValue();
    }

    /**
     * 通过Key从缓存中获取数据
     *
     * @param key key
     * @return obj
     */
    public AnalysisConfigParamDTO getFromCacheKey(String key) {
        return getFromCacheKey(key, -1);
    }

    public AnalysisConfigParamDTO getFromCacheKey(String key, Integer entId) {
        if (StringUtils.isBlank(key)) {
            return null;
        }

        //不同企业相同KEY下要区分
        String newKey = key + "_" + entId;

        if (entId == null || entId <= 0) {
            newKey = key + "_" + helpService.getEnterpriseId();
        }

        AnalysisConfigParamDTO obj = jedisCache.oget(KeyConstants.CONFIGPARAM_INFO_KEY + newKey, AnalysisConfigParamDTO.class);
        if (obj == null) {
            obj = getByParamKey(key);
            if (obj != null) {
                jedisCache.oset(KeyConstants.CONFIGPARAM_INFO_KEY + newKey, obj);
            }
        }

        return obj;
    }

    /**
     * 刷新缓存
     *
     * @param id 参数id
     */
    private void refreshCacheById(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        AnalysisConfigParamDTO obj = getById(id);
        if (obj != null) {
            //不同企业相同KEY下要区分
            jedisCache.delete(KeyConstants.CONFIGPARAM_INFO_KEY + obj.getParamKey() + "_" + obj.getEntId());
        }
    }

    /**
     * 刷新缓存(批量)
     *
     * @param idList ids
     */
    private void refreshCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshCacheById(id);
        }
    }
}